<!-- 逆变器报表 -->
<template>
  <div class="content">
    <h4 id="title">电站概览</h4>
    <!-- 标题 -->
    <div class="title">
      <div class="time-box">
        <!-- 年月日选择 --><!-- 选择查询 -->
        <el-date-picker v-model="timeValue" type="daterange" format="YYYY/MM/DD" value-format="YYYY-MM-DD" range-separator="-" :start-placeholder="$t('licence.use_kaishi')"
          :end-placeholder="$t('licence.use_jieshu')" :picker-options="pickerOptions">
        </el-date-picker>
        <el-button :disabled="disabled" @click="getStationOverview" type="primary" style="margin: 0 20px">{{
          $t('licence.fau_Thequery') }}</el-button>
      </div>
      <!-- 导出 -->

      <div style="display: flex">
        <div class="export" @click="ExportPDF()">
          {{ $t('licence.sta_exportPDF') }}
        </div>
        <div class="export" @click="ExportExl()">
          {{ $t('licence.sta_exportExl') }}
        </div>
      </div>
    </div>
    <div ref="divExport" v-loading="loading">
      <h4 class="stationName">
        {{ powerStation.stationName }}({{ timeValue[0] }} ~ {{ timeValue[1] }})
      </h4>
      <!-- 电站概览 -->
      <div class="table" style="width: 100%">
        <el-table :data="tableData" row-key="id" :span-method="objectSpanMethod" :summary-method="getSummaries"
          show-summary border>
          <el-table-column align="center" prop="stationName" label="电站名称"></el-table-column>
          <el-table-column align="center" prop="gatLabel" label="DTU单元SN"></el-table-column>
          <el-table-column align="center" prop="psLabel" label="逆变器SN（运行天数）"></el-table-column>
          <el-table-column align="center" prop="date" label="时间">
          </el-table-column>
          <el-table-column align="center" prop="electricity" label="日发电量（kWh）"></el-table-column>
          <el-table-column width="300px" align="center" prop="equivalentHours" label="等效小时数（发电量/装机功率）h"></el-table-column>
          <el-table-column align="center" prop="maxPower" label="当日最大功率（W）"></el-table-column>
          <el-table-column align="center" prop="maxTemperature" label="当日最高温度"></el-table-column>
        </el-table>
      </div>
      <!-- 数据曲线图 -->
      <div id="echarts" ref="divExportExl">
        <h4 id="title" style="margin-top: 30px" v-if="psChartsDataGroup.length">电站曲线</h4>
        <div class="echart-container" v-for="(item1, index1) in psChartsDataGroup" :key="index1">
          <h1>{{ item1.date }}</h1>
          <div>
            <div v-for="(item2, index2) in item1.chartsVos" :key="index2" class="echarts-item">
              <h4 id="title">{{ item2.series[0].name }}</h4>
              <div :id="item1.date + index2" style="height: 560px"></div>
            </div>
          </div>
          <!-- 日发电量柱状图 -->
        </div>
        <div class="ECH">
          <div class="zhu">
            <h4 id="title">发电量</h4>
            <div id="echarts7"></div>
          </div>
          <div class="zhu">
            <h4 id="title">等效小时</h4>
            <div id="echarts8"></div>
          </div>
        </div>
      </div>
      <!-- 故障信息 -->
      <div>
        <h4 id="title" style="margin: 30px 0 30px 0">故障信息</h4>
        <div class="table" style="width: 100%">
          <el-table :data="psDescListData" :span-method="objectSpan" border>
            <el-table-column align="center" prop="label" label="S/N码（故障个数）"></el-table-column>

            <el-table-column align="center" prop="code" label="故障编码"></el-table-column>
            <el-table-column align="center" prop="desc" :show-overflow-tooltip="true" label="故障详情"></el-table-column>
            <el-table-column align="center" prop="startTime" label="开始时间">
            </el-table-column>
            <el-table-column align="center" prop="endTime" label="结束时间">
            </el-table-column>
            <el-table-column align="center" prop="frequencyPs" label="故障总频次/同一机器"></el-table-column>
            <el-table-column align="center" prop="frequencyStation" label="故障总频次/同一电站"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="Data2">
import * as echarts from "echarts";
import { getStationOverviewT, getForDevExp } from "@/api/monitor/diagram";
import { requestData } from "./222.js";
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
import { printPdf } from "@/utils/html2canvas";
import html2canvas from "html2canvas";
import { ElLoading, type TableColumnCtx } from 'element-plus'
      const onday = ref('')
      const pickerOptions = ref({
        onPick: (time:any) => {
          if (time.minDate && !time.maxDate) {
            onday.value = time.minDate;
          }
          if (time.maxDate) {
            onday.value = "";
          }
        },
        disabledDate: (time:any) => {
          let timeone = onday.value;
          let secondNum = 60 * 60 * 24 * 6 * 1000;
          if (onday.value != "") {
            return (
              new Date(timeone).getTime() + secondNum < time.getTime() ||
              time.getTime() > Date.now() ||
              new Date(timeone).getTime() - secondNum > time.getTime()
            );
          } else {
            return time.getTime() > Date.now();
          }
        },
      })
      //=============
      // 时间选择器
      const getNowTime = () => {
        const start = new Date(new Date().getTime() - 3600 * 1000 * 24)
          .toISOString()
          .substring(0, 10)
          .split(".")[0]; //默认开始时间1天前
        const end = new Date(new Date().getTime() - 3600 * 1000 * 24)
          .toISOString()
          .substring(0, 10)
          .split(".")[0]; //默认结束时间1天前
          return [start, end];
      }
    const timeValue = ref(getNowTime()) //日期选择

    const lang = ref(0)
    const loading = ref(false)
    const divExport = ref()
    const divExportExl = ref()
    interface User {
      id: string
      name: string
      amount1: string
      amount2: string
      amount3: number
    }
    interface SpanMethodProps {
      row: User
      column: TableColumnCtx<User>
      rowIndex: number
      columnIndex: number
    }
    // const fullscreenLoading = ref(false)
    const powerStation= ref({
      id:-1,
      stationName:''
    }) //获取保存电站信息
    // 电站概览
    const tableData = ref([])
    const psDescListData = ref([])
    const avg = ["electricity", "equivalentHours", "maxPower", "maxTemperature"] //求和的字段和求平均数的字段名字
    const psChartsDataGroup = ref([{
      date:'',
      chartsVos:[],
      series:[{
        name:''
      }]
    }]) //保存每天数据
    const disabled = ref(false)

    onMounted(()=>{
      // 获取语言
      if (localStorage.getItem("locale") == "en_US") {
        lang.value = 1;
      } else {
        lang.value = 0;
      }
      // 获取电站信息
      powerStation.value = JSON.parse(localStorage.getItem("powerStation") as string);
      getStationOverview();
    })

    const getStationOverview = async() => {
      loading.value = true;
      disabled.value = true;
      let res = await getStationOverviewT({
        stationId: powerStation.value.id,
        lang: lang.value,
        startDay: timeValue.value[0],
        endDay: timeValue.value[1],
      });
      tableData.value = res.data.viewsList ? res.data.viewsList : [];
      psDescListData.value = res.data.psDescList? res.data.psDescList : [];
      psChartsDataGroup.value = res.data.psCharts? res.data.psCharts : [];// 接口 数据
      if (res.data.psCharts) {
        // 第一层 日期
        psChartsDataGroup.value.forEach((item1, index1) => {
          //  第二层 图标表
          item1.chartsVos.forEach((item2:any, index2:any) => {
            let series:any = [];
            // 处理series数据
            item2.series.forEach((item3:any, index3:any) => {
              series.push({
                name: item3.source,
                type: "line",
                showSymbol: false, //不显示折线图上的圆点
                smooth: true,
                //  stack: 'Total',
                lineStyle: {
                  width: 1, //设置线条粗细
                },
                data: item3.data,
              });
            });
            let domId = `${item1.date + index2}`;
            nextTick(() => {
              getEchartsByDate(domId, item2.categories, series);
            });
          });
        });
      } else {
        return;
      }
      if (res.data.ucharts) {
        // // 固定柱状图
        nextTick(() => {
          getEcharts7(res.data.ucharts[0]);
          getEcharts8(res.data.ucharts[1]);
        });
      } else {
        return;
      }
      loading.value = false;
      disabled.value = false;
      // 展示图表
    }

    //1
    const getEchartsByDate = (domId:any, data:any, series:any)=>  {
      const myChart = echarts.init(document.getElementById(domId) as HTMLElement)as echarts.ECharts;
      myChart.setOption({
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          icon: "circle",
        },
        // 位置
        grid: {
          top: "30%", //距上边距
          left: "2%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data,
        },
        yAxis: [
          {
            type: "value",
            // name: "发电量1",
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
            },
            min: 0,
          },
        ],
        series,
      });
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
    // 日发电量柱状图
    const getEcharts7 = (data:any) => {
      const myChart = echarts.init(document.getElementById("echarts7") as HTMLElement)as echarts.ECharts;
      myChart.setOption({
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          icon: "circle",
        },
        // 位置
        grid: {
          // left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.categories,
        },
        yAxis: [
          {
            type: "value",
            name: data.series[0].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
            },
            min: 0,
          },
        ],
        series: [
          {
            name: data.series[0].name,
            data: data.series[0].data,
            type: "bar",
            barWidth: "16",
            barGap: 7,
            itemStyle: {
              color: "#305ADD",
            },
          },
        ],
      });
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
    // 总等效小时的柱状图
    const getEcharts8 = (data:any) => {
      const myChart = echarts.init(document.getElementById("echarts8") as HTMLElement)as echarts.ECharts;
      myChart.setOption({
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          icon: "circle",
        },
        // 位置
        grid: {
          // left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.categories,
        },
        yAxis: [
          {
            type: "value",
            name: data.series[0].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
            },
            min: 0,
          },
        ],
        series: [
          {
            name: data.series[0].name,
            data: data.series[0].data,
            type: "bar",
            barWidth: "16",
            barGap: 7,
            itemStyle: {
              color: "#305ADD",
            },
          },
        ],
      });
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
    const echartsToBase64 = (dom:any) => {
      try {
        let ech = echarts.getInstanceByDom(dom);
        let baseUrl = ech.getDataURL({
          type: "png",
          backgroundColor: "#fff",
        });
        return baseUrl;
      } catch (err) {
        return "";
      }
    }
    // 导出
    const ExportPDF = async() =>{
      const loading =  ElLoading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 个人业务，获取名字用来当pdf文件名
      let comNameHid = "逆变器"; // 抓取要截图的div的class名  也可以使用ref进行获取
      let target =divExport.value; // pdf背景色
      target.style.background = "#FFFFFF"; // 滚动条置顶，避免截图不全，截图是从当前浏览器看的位置开始截取的
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0; // pdf工具
      printPdf(comNameHid, target);

      setTimeout(() => {
        loading.close();
      }, 2000);
    }
    // 导出
    const ExportExl = () => {
      const loading =  ElLoading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var powerStationId = String(powerStation.value.id);
      var timeValueO = timeValue.value[0];
      var timeValueT = timeValue.value[1];
      var nameBiao = t("licence.inv_tongji");
      var dataUrl;
      var canvas2 = document.createElement("canvas"); //创建一个新的canvas
      let _canvas = document.querySelector("#echarts") as HTMLElement; //这里面填写 你需要截图的div
      var w = parseInt(window.getComputedStyle(_canvas).width);
      var h = parseInt(window.getComputedStyle(_canvas).height);
      canvas2.width = w;
      canvas2.height = h; //将canvas画布放大2倍或者更多，然后盛放在较小的容器内，就显得不模糊了
      canvas2.style.width = w + "px";
      canvas2.style.height = h + "px";

      var context = canvas2.getContext("2d") as CanvasRenderingContext2D ;
      context.scale(1, 1); //指图片偏移
      html2canvas(_canvas, {
        //写需要截图的div
        // taintTest: false,
        useCORS: true,
        allowTaint: false, //这三串代码解决跨域问题
        canvas: canvas2,
      }).then(async (canvas:any) => {
        dataUrl = canvas.toDataURL("image/png");
        var arr = dataUrl.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        var suffix = mime.split("/")[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        var filename = "temp_img";
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        var file = new File([u8arr], `${filename}.${suffix}`, { type: mime });
        var formdata = new FormData();
        formdata.append("file", file);
        formdata.append("stationId", powerStationId);
        formdata.append("startDay", timeValueO);
        formdata.append("endDay", timeValueT);
        formdata.append("lang", lang.value);
        const res = await getForDevExp(formdata);
        let url = window.URL.createObjectURL(
          new Blob([res], { type: "application/vnd.ms-excel" })
        );
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", nameBiao + ".xls");
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          loading.close();
        }, 2000);
      });
    }
    const objectSpanMethod = ({ row:any, column, rowIndex, columnIndex }:SpanMethodProps) =>{
      let data = tableData.value; //拿到当前table中数据
      let cellValue = row[column.property]; //当前位置的值
      let noSortArr = [
        "days",
        "date",
        "electricity",
        "equivalentHours",
        "maxPower",
        "maxTemperature",
      ]; //不需要合并的字段（不进行合并行的prop）
      if (cellValue && !noSortArr.includes(column.property)) {
        let prevRow = data[rowIndex - 1]; //获取到上一条数据
        let nextRow = data[rowIndex + 1]; //下一条数据
        if (prevRow && prevRow[column.property] === cellValue) {
          //当有上一条数据，并且和当前值相等时
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            //当有下一条数据并且和当前值相等时,获取新的下一条
            nextRow = data[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    }
    const objectSpan = ({ row:any, column, rowIndex, columnIndex }:SpanMethodProps) =>{
      let data = psDescListData.value; //拿到当前table中数据
      let cellValue = row[column.property]; //当前位置的值
      let noSortArr = [
        "code",
        "desc",
        "startTime",
        "endTime",
        "frequencyPs",
        "frequencyStation",
      ]; //不需要合并的字段（不进行合并行的prop）
      if (cellValue && !noSortArr.includes(column.property)) {
        let prevRow = data[rowIndex - 1]; //获取到上一条数据
        let nextRow = data[rowIndex + 1]; //下一条数据
        if (prevRow && prevRow[column.property] === cellValue) {
          //当有上一条数据，并且和当前值相等时
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            //当有下一条数据并且和当前值相等时,获取新的下一条
            nextRow = data[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    }
    // 表尾合计
    const getSummaries = (param:any) =>{
      if (tableData.value == null) {
        return;
      } else {
        const { columns, data } = param;
        const sums:any = [];
        columns.forEach((column:any, index:any) => {
          if (index === 0) {
            sums[index] = "均值参数";
            return;
          }
          const sumList:any[] = [];
          const avgList = avg || [];
          const values = data.map((item:any) => {
            return Number(item[column.property]);
          });

          if (
            sumList.includes(column.property) ||
            avgList.includes(column.property)
          ) {
            let totalCount = 0; // 求平均数使用
            sums[index] = values.reduce((prev:number, curr:number) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                totalCount++;
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if (avgList.includes(column.property) && totalCount) {
              sums[index] = sums[index] / totalCount;
              sums[index] = sums[index].toFixed(2);
            }
          } else {
            sums[index] = "";
          }
        });
        return sums;
      }
    }
</script>
<style scoped lang="scss">
* {
  margin: 0;
  box-sizing: border-box;
  list-style: none;
}

.stationName {
  text-align: center;
  font-weight: 600;
  font-size: 20px;
  margin-top: 30px;
  margin-bottom: 30px;
}

.content {
  background-color: #fff;
  //   height: 100%;
  padding: 20px 20px 50px 20px;
  border-radius: 6px;

  //   时间 导出 标题
  #title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #0e1319;
  }

  .title {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;

    // 查询按钮
    .el-button--primary {
      color: #ffffff;
      background-color: #305add;
      border-color: #305add;
    }

    //导出
    .export {
      width: 90px;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #dddfe6;
      font-size: 14px;
      text-align: center;
      line-height: 36px;
      cursor: pointer;
      margin-left: 20px;
    }
  }

  // 表格样式
  ::v-deep .el-table .cell {
    padding-left: 0px;
    padding-right: 0px;
  }

  ::v-deep .el-table .el-table__cell {
    padding: 6px 0;
  }

  ::v-deep .el-table__footer-wrapper tbody td.el-table__cell {
    background-color: transparent;
  }

  // 图表的展示
  #echarts {
    margin-top: 30px;

    #title {
      margin-bottom: 30px;
      margin-top: 30px;
    }

    .echart-container {
      // width: 100%;
      // display: flex;
      // // flex-wrap: nowrap;
      // .echarts-item {
      //   // flex: 0.5;
      //   width: 40%;
      // }
    }

    .ECH {
      // 日发电量柱状图
      display: flex;
      justify-content: space-between;

      .zhu {
        flex: 0.5;

        #echarts7,
        #echarts8 {
          height: 560px;
          //   background-color: #f8f9fb;
        }
      }
    }
  }
}
</style>
<style>
.el-tooltip__popper {
  max-width: 40%;
}
</style>
